package cn.ren.controller;

import cn.ren.constant.MessageConstant;
import cn.ren.constant.RedisMessageConstant;
import cn.ren.entity.Result;
import cn.ren.pojo.Order;
import cn.ren.service.OrderService;
import cn.ren.util.SMSUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @program: itcast_health
 * @description: 预定体检
 * @author: ren
 * @create: 2020-03-01 10:34
 **/
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String)map.get("telephone");
        //和redis里保存的验证码对比
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String codeInForm = (String)map.get("validateCode");
        if (codeInForm == null || codeInRedis == null || !(codeInForm.equals(codeInRedis))){
            //验证码验证不通过
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //通过dubbo网络服务，保存预约信息到数据库
        Result result = null;
        map.put("orderType", Order.ORDERTYPE_WEIXIN);
        try {
            result = orderService.order(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
        //对order方法返回的结果进行判断
        if (result.isFlag()){
            //预约成功，发送成功短信
            String orderDate = (String)map.get("orderDate");
            String notice = orderDate.replaceAll("-", "");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,notice);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            //查询预约信息成功
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            //查询预约信息失败
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
